package com.promise.jokerdream.work.faction

import com.promise.jokerdream.manager.ExecutionHistoryManager
import com.promise.jokerdream.repository.GameApi
import com.promise.jokerdream.repository.foldWithApiException
import com.promise.jokerdream.utils.AppContext
import com.promise.jokerdream.work.BaseWork
import com.promise.jokerdream.work.WorkResult

// 问鼎天下工作
class FactionTerritoryWork(uin: String): BaseWork(uin) {
    
    private val gameApi = GameApi.getInstance()
    private val historyManager by lazy { ExecutionHistoryManager.getInstance(AppContext.get()) }
    
    override val name: String
        get() = "问鼎天下"
    
    override suspend fun executeWork(): WorkResult {
        return try {
            // 查询问鼎天下信息
            val queryResult = gameApi.queryTBattle()
            queryResult.foldWithApiException(
                onSuccess = { response ->
                    // 处理区域赛助威
                    if (response.rb.canCheer == 1 && response.rb.cheeredFactionId == 0) {
                        val factionId = 96690
                        val cheerResult = gameApi.cheerRegionBattle(factionId)
                        cheerResult.foldWithApiException(
                            onSuccess = { cheerResponse ->
                                historyManager.addHistory(name, cheerResponse.getDescription())
                            },
                            onFailure = { code, msg ->
                                historyManager.addHistory(name, msg)
                            }
                        )
                    }
                    
                    // 处理冠军赛助威
                    if (response.cb.canCheer == 1 && response.cb.cheeredFactionId == 0) {
                        val factionId = 96690
                        val cheerResult = gameApi.cheerChampionBattle(factionId)
                        cheerResult.foldWithApiException(
                            onSuccess = { cheerResponse ->
                                historyManager.addHistory(name, cheerResponse.getDescription())
                            },
                            onFailure = { code, msg ->
                                historyManager.addHistory(name, msg)
                            }
                        )
                    }
                    
                    WorkResult.Success
                },
                onFailure = { code, msg ->
                    historyManager.addHistory(name, msg)
                    WorkResult.Failure(Exception(msg), msg)
                }
            )
        } catch (e: Exception) {
            historyManager.addHistory(name, e.message)
            WorkResult.Failure(e, e.message)
        }
    }
}